//验证浏览器是否支持WebSocket协议
if (!window.WebSocket) {
    alert("您的浏览器不支持webSocket！");
}

$select = function(id) {
    return document.getElementById(id);
};
toast = function(text){
    Materialize.toast(text, 4000)
}
var webChat = {
    domain: "",
    ws : null,
    userId : 0,
    toUserId : 0,
    user : "",
    avatar : "",
    isLinkWs : false,
    avatarList : [
        "img/avatar/avatar_0.jpg",
        "img/avatar/avatar_1.jpg",
        "img/avatar/avatar_2.jpg",
        "img/avatar/avatar_3.jpg",
        "img/avatar/avatar_4.jpg",
        "img/avatar/avatar_5.jpg",
        "img/avatar/avatar_6.jpg",
        "img/avatar/avatar_7.jpg",
        "img/avatar/avatar_8.jpg",
        "img/avatar/avatar_9.jpg",
        "img/avatar/avatar_10.jpg",
        "img/avatar/avatar_11.jpg"
    ]
};
webChat.Init = function (domain) {
    this.domain = domain;
    this.bindEvent();
    this.checkAvatar();
    return this;
};
webChat.conn = function(){
    if(this.isLinkWs){
        return false;
    }
    if ($select('user').value == ""){
        toast('请输入一个昵称');
        return false;
    }
    $select('link_href').innerHTML = "连接中...";
    this.ws = new WebSocket(this.domain);
    this.isLinkWs = true;
    this.user = $select('user').value;
    var _that = this;
    this.ws.onmessage = function(event) {
        // console.log(event.data);
        _that.analysis(event.data);
    };
    this.ws.onclose = function(event) {
        toast("连接已关闭");
    };
    this.ws.onopen = function(event) {
        $select('link_href').innerHTML = "连接";
        $select('wait_link').style.display = "none";
        $select('linked').style.display = "block";
        $select('nicknameSpan').innerHTML = _that.user;
        $select('avatarImg').src = _that.avatar;
        $select('onlineList').style.display = "block";
        var msg = _that.message("notify",_that.userId,"","system",_that.user +' 加入群聊');
        _that.ws.send(msg);
    };
    ws.onerror =function(event){
    };
};
webChat.bindEvent = function (){
    var _that = this;
    $select('link_href').addEventListener('click',function(){
        _that.conn();
    });
    $select('checkAvatar').addEventListener('click',function(){
        _that.checkAvatar();
    });
    $select('send').addEventListener('click',function(){
        _that.sendMsg();
    });
    document.addEventListener('keydown',function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if(e && e.keyCode==27){ // 按 Esc
            toast("ESC退出")
        }
        if(e && e.keyCode==113){ // 按 F2
            toast("F2");
        }
        if (e.keyCode == 13 && e.ctrlKey) {
            toast("你按下了ctrl+Enter");
            //添加换行
            $select("body").value += "\n";
        }else if(e && e.keyCode==13){ // enter 键
            e.preventDefault();//阻止换行
            _that.sendMsg();
        }

    });

};
webChat.sendMsg = function(){
    var msg = this.bodyMsg();
    $select("body").value = "";
    this.ws.send(msg);
};
webChat.bodyMsg = function(){
    var body = $select("body").value;
    body = body.replace(/\r/g,"&nbsp;");
    body = body.replace(/\n/g,"<br />");
    return this.message("user",this.userId,this.avatar,this.user,body);
};
webChat.message = function (type,userId,avatar,user,body) {
    var message = {
        "type":type,
        "user_id":userId,
        "avatar":avatar,
        "user":user,
        "body":body,
        "to_user_id":this.toUserId
    };
    return JSON.stringify(message);
}
webChat.analysis = function(s){
    if (document.readyState !== "complete") {
        log.buffer.push(s);
    } else {
        var msgObj = JSON.parse(s);
        var msgDom = "";
        switch (msgObj.type){
            case "user":
                if (msgObj.user_id == this.userId){
                    //自己发的信息
                    msgDom = this.rightDom(msgObj.avatar,msgObj.user,msgObj.body);
                }else{
                    //其他信息
                    msgDom = this.leftDom(msgObj.avatar,msgObj.user,msgObj.body);
                    this.notify(msgObj.avatar,msgObj.user,msgObj.body)
                }
                $select("msgList").innerHTML += (msgDom + "\n");
                break;
            case "system":
                if (msgObj.user == "online"){
                    console.log(msgObj.user_list);
                    $select('online').innerText = msgObj.body;
                    var onlineList = "";
                    var users = msgObj.user_list;
                    for( var value in users){
                        alert(value.user_id)
                        onlineList += '<div class="chip"><img src="' + value.avatar + '" alt="Contact Person">'+ value.nickname +'</div>';
                    }
                    $select("onlineBox").innerHTML(onlineList);
                }
                break;
            case "notify":
                if (msgObj.user == "message"){
                    this.userId = msgObj.user_id;
                }
                msgDom = this.centerDom(msgObj.body);
                $select("msgList").innerHTML += (msgDom + "\n");
                break;
            default:
                break;
        }
        $select("msgList").scrollTop = $select("msgList").scrollHeight;
    }
};
webChat.checkAvatar = function () {
    if(this.isLinkWs){
        return false;
    }
    var len = this.avatarList.length;
    var index = Math.random() * len;
    index = Math.floor(index);
    var img = this.avatarList[index];
    this.avatar = img
    $select("avatar").src = img
};
webChat.leftDom = function (avatar,user,body) {
    return '<div class="msg-item">'+
        '<div class="left-item">'+
        '<div class="avatar left">'+
        '<img class="circle" src="' + avatar + '" width="40" height="40" />'+
        '</div>'+
        '<div class="content left-align">'+
        '<div class="nickname">' + user + '</div>'+
        '<span>' + body + '</span>'+
        '</div>'+
        '</div>'+
        '</div>';
};
webChat.rightDom = function (avatar,user,body) {
    return '<div class="msg-item">'+
        '<div class="right-item">'+
        '<div class="avatar right">'+
        '<img class="circle" src="' + avatar + '" width="40" height="40" />'+
        '</div>'+
        '<div class="content right-align">'+
        '<div class="nickname">' + user + '</div>'+
        '<span>' + body + '</span>'+
        '</div>'+
        '</div>'+
        '</div>';
};
webChat.centerDom = function (body) {
    return '<div class="msg-item"><span class="system">' + body + '</span></div>';
};
webChat.notify = function (icon,title,body) {
    Notification.requestPermission(function (perm) {
        if (perm == "granted") {
            var notification = new Notification(title, {
                dir: "auto",
                lang: "hi",
                tag: "testTag",
                icon: icon,
                body: body
            });
        }
    })
};
